package vrp;

import java.io.IOException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import vrp.PMF;
import vrp.Customer;
import vrp.Distance;

public class CustomerAddServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {

        PersistenceManager pm = PMF.get().getPersistenceManager();

        long parterID = Integer.parseInt(req.getParameter("partner"));
        Key partnerKey = KeyFactory.createKey(Partner.class.getSimpleName(), parterID);
        String name = req.getParameter("name");
        String address = req.getParameter("address");
        String postalCode = req.getParameter("postalCode");
        String contactNo = req.getParameter("contactNo");
        double lat = Float.parseFloat(req.getParameter("lat"));
        double lng = Float.parseFloat(req.getParameter("lng"));
        boolean isDepot = Boolean.parseBoolean(req.getParameter("isDepot"));
        String distances = req.getParameter("distances");
        
        String respondRedirect = "";
        if (isDepot == true) {
        	respondRedirect = "/depots.jsp";
        } else {
        	respondRedirect = "/customers.jsp";
        }

        long customerID = 0;
        try {
        	Customer customer = new Customer(partnerKey, name, address, postalCode, contactNo, lat, lng, isDepot);
            Customer newcustomer = pm.makePersistent(customer);
            customerID = newcustomer.getKey().getId();
            
            if (!distances.equals("")){
	            String[] customers = distances.split("-");
	            for (String c: customers){
	            	String[] components = c.split(" ");
	            	int cid = Integer.parseInt(components[0]);
	            	if (cid!=customerID){
		            	double from = Float.parseFloat(components[1]);
		            	double to = Float.parseFloat(components[2]);
		            	Distance distance1 = new Distance(customerID,cid,to);
		            	Distance distance2 = new Distance(cid,customerID,from);
		            	pm.makePersistent(distance1);
		            	pm.makePersistent(distance2);
	            	}
	            }
            }
        } finally {
            pm.close();
        }
        resp.sendRedirect(respondRedirect);
    }
}
